import pandas as pd
from py2neo import Graph, Node, Relationship

# 连接到 Neo4j
graph = Graph("bolt://localhost:7687", auth=("neo4j", "714716liu"))

# 读取 Excel 文件
excel_file = "C://code//Python//machine-learning-summary//Data//nodes.xlsx"
excel_file2 = "C://code//Python//machine-learning-summary//Data//relationships.xlsx"

# 读取节点表
nodes_df = pd.read_excel(excel_file, sheet_name="Nodes")
print(nodes_df)
#print(nodes_df.columns)
#data1 = nodes_df.loc[1]
#print(data1[0])
#print(type(data1))
#quit()

# 读取关系表
relationships_df = pd.read_excel(excel_file2, sheet_name="Relationships")
#print(relationships_df)

# 添加节点到图数据库
for _, row in nodes_df.iterrows():
    node_type = row["Type"]
    node = Node(node_type, Name=row["Label"], Type=row["Type"])
    for col in nodes_df.columns:
        if col not in ["Node_ID", "Label", "Type"]:
            node[col] = row[col]  # 添加其他属性
    graph.merge(node, node_type, "Name")  # 根据 name 唯一性合并节点

# 添加关系到图数据库
for _, row in relationships_df.iterrows():
    source_node = graph.nodes.match("Knowledge", Name=row["Source_Name"]).first()
    target_node = graph.nodes.match("Knowledge", Name=row["Target_Name"]).first()
    if source_node and target_node:
        relationship = Relationship(source_node, row["Relationship"], target_node)
        for col in relationships_df.columns:
            if col not in ["Source_Name", "Target_Name", "Relationship"]:
                relationship[col] = row[col]  # 添加其他属性
        graph.merge(relationship)